// 加载下一页
import { use, useState, Suspense } from "react";
import PropTypes from "prop-types";
function fetchPageData(page) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const pageData = Array.from(
        { length: 5 },
        (_, index) => `第${page}页的数据项${index + 1}`
      );
      resolve(pageData);
    }, 1000);
  });
}
function PageData({ pagePromise }) {
  const data = use(pagePromise);
  return (
    <>
      {data.map((item, index) => (
        <li key={index}>{item}</li>
      ))}
    </>
  );
}
PageData.propTypes = {
  pagePromise: PropTypes.arrayOf(PropTypes.object).isRequired,
};
function App() {
  const [currentPage, setCurrentPage] = useState(1);
  const [pages, setPages] = useState(() => [fetchPageData(currentPage)]);
  return (
    <>
      <ul>
        {pages.map((pagePromise, index) => (
          <Suspense key={index} fallback={<div>正在加载{index + 1}页...</div>}>
            <PageData pagePromise={pagePromise} />
          </Suspense>
        ))}
      </ul>
      <button
        onClick={() => {
          const nextPage = currentPage + 1;
          setCurrentPage(nextPage);
          setPages([...pages, fetchPageData(nextPage)]);
        }}
      >
        加载下一页
      </button>
    </>
  );
}
export default App;
//异步调用接口获取返回的数据进行渲染
